//
//  NavigatingViewController.m
//  EZ Tracker
//
//  Created by FENGYL on 2016/11/28.
//  Copyright © 2016年 FENGYL. All rights reserved.
//

#import "NavigatingViewController.h"
#import "TotalDeviceSelectedViewController.h"
#import "PullUpMenuView.h"
#import "KCAnnotation.h"
#import "UserModel.h"
#import "NetworkCommand.h"
#import "WGS84TOGCJ02.h"
#import "MsgCommand.h"

#import <MBProgressHUD.h>
#import <CoreLocation/CoreLocation.h>
#import <MapKit/MapKit.h>
#import <SVProgressHUD.h>

@interface NavigatingViewController ()<MKMapViewDelegate>

@property (strong , nonatomic) CLLocationManager * locationManager;
@property (strong , nonatomic) MKMapView *mapView;

@property (strong , nonatomic) PullUpMenuView * pullUpView;
@property (strong , nonatomic) UIView * coverView;

@property (strong, nonatomic) UserModel *userModel;

@property (strong, nonatomic) KCAnnotation *annotation;

@property (strong, nonatomic) MsgCommand *msgCommand;

@property (strong, nonatomic) NSMutableArray *polylineArray;

@property (strong, nonatomic) NSMutableArray *updatePolylineArray;

@property (strong, nonatomic) NSMutableArray *lineViewArray;

@property (strong, nonatomic) MKMapItem *nowAnnotaionMapItem;

@property (weak, nonatomic) IBOutlet UIButton *satelliteButton;
@property (weak, nonatomic) IBOutlet UIButton *fullScreenButton;
@property (weak, nonatomic) IBOutlet UIButton *locationButton;
@property (weak, nonatomic) IBOutlet UIView *topButtonView;

@property (weak, nonatomic) IBOutlet UIView *topView;
@property (weak, nonatomic) IBOutlet UIButton *topArrowButton;
@property (weak, nonatomic) IBOutlet UILabel *topLabel;
@property (weak, nonatomic) IBOutlet UIButton *topGetLastestLocationButton;

@property (weak, nonatomic) IBOutlet UIView *bottomView;
@property (weak, nonatomic) IBOutlet UIButton *bottomArrowButton;
@property (weak, nonatomic) IBOutlet UILabel *bottomLabel;
@property (weak, nonatomic) IBOutlet UIButton *bottomGetLastestLocationButton;

@property (weak, nonatomic) IBOutlet UIBarButtonItem *listSelectBarButtonItem;


@end

@implementation NavigatingViewController

-(UserModel *)userModel{
    
    if (!_userModel) {
        
        _userModel = [[UserModel alloc]init];
        
    }
    
    return _userModel;
    
}

-(MsgCommand *)msgCommand{
    
    if (!_msgCommand) {
        _msgCommand = [[MsgCommand alloc]init];
    }
    return _msgCommand;
}

-(NSMutableArray *)polylineArray{
    
    if (!_polylineArray) {
        _polylineArray = [NSMutableArray array];
    }
    return _polylineArray;
}

-(NSMutableArray *)updatePolylineArray{
    
    if (!_updatePolylineArray) {
        _updatePolylineArray = [NSMutableArray array];
    }
    return _updatePolylineArray;
}

-(NSMutableArray *)lineViewArray{
    
    if (!_lineViewArray) {
        _lineViewArray = [NSMutableArray array];
    }
    return _lineViewArray;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    //设置阴影
    [self setViewShadow:self.topButtonView];
    [self setViewShadow:self.topView];
    [self setViewShadow:self.bottomView];
    
    //初始化地图
    [self locationEnable];
    [self setMap];
    
    //初始化两个view
    [self.topLabel setText:@""];
    [self.bottomLabel setText:@""];
    
    self.satelliteButton.selected = NO;
    self.fullScreenButton.selected = NO;
    
    self.topArrowButton.selected = NO;
    self.bottomArrowButton.selected = NO;
    
    //设置页面跳转没有列表按钮
    if (_isSetting) {
        
        self.navigationItem.rightBarButtonItem = nil;
        
    }
    
    [self searchLocation];
    
    
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

-(void)viewDidAppear:(BOOL)animated{
    
    //打开屏幕常亮
    [[UIApplication sharedApplication] setIdleTimerDisabled:YES];
    
}

-(void)viewDidDisappear:(BOOL)animated{
    
    //关闭屏幕常亮
    [[UIApplication sharedApplication] setIdleTimerDisabled:NO];
    
}

-(void)viewWillAppear:(BOOL)animated{
    
    [self setPullUpMenu];
    
}

-(void)viewWillDisappear:(BOOL)animated{
    
    [self.coverView removeFromSuperview];
    [self.pullUpView removeFromSuperview];
    
    self.fullScreenButton.selected = NO;
    [self.navigationController setNavigationBarHidden:NO animated:YES];
    
}

#pragma mark 初始化上拉菜单
-(void)setPullUpMenu{
    
    UIWindow * window = [UIApplication sharedApplication].keyWindow;
    
    self.pullUpView = [[PullUpMenuView alloc]initWithPullUpMenuView];
    
    [self setViewShadow:self.pullUpView];
    
    self.coverView = [[UIView alloc]initWithFrame:CGRectMake(0, [[UIApplication sharedApplication] statusBarFrame].size.height, [UIScreen mainScreen].bounds.size.width, [UIScreen mainScreen].bounds.size.height - [[UIApplication sharedApplication] statusBarFrame].size.height)];
    
    [self.coverView setBackgroundColor:[UIColor blackColor]];
    
    __block NavigatingViewController * safeSelf = self;
    
    self.pullUpView.changeCoverViewAlpha = ^(CGFloat pullUpMenuViewY){
        
        safeSelf.coverView.alpha = ([UIScreen mainScreen].bounds.size.height - pullUpMenuViewY - 30) / ([UIScreen mainScreen].bounds.size.height - [[UIApplication sharedApplication] statusBarFrame].size.height - 30) / 2;
        
    };
    
    self.coverView.alpha = 0;
    
    [window addSubview:self.coverView];
    
    [window addSubview:self.pullUpView];
    
}

#pragma mark 按钮阴影效果
-(void)setViewShadow:(UIView *)sender{
    
    sender.layer.shadowColor = [UIColor blackColor].CGColor;
    
    sender.layer.shadowOffset = CGSizeMake(2, 2);
    
    sender.layer.shadowOpacity = 0.4;
    
    sender.layer.shadowRadius = 4;
    
}

#pragma mark 初始化地图

-(void)setMap{
    
    self.mapView = [[MKMapView alloc]initWithFrame:CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.width, [UIScreen mainScreen].bounds.size.height)];
    
    [self.view addSubview:self.mapView];
    
    [self.view sendSubviewToBack:self.mapView];
    
    self.mapView.delegate = self;
    
    self.mapView.userTrackingMode = MKUserTrackingModeFollow;
    
    self.mapView.mapType = MKMapTypeStandard;
    
    
    
    
}

#pragma mark 判断是否有权限
-(void)locationEnable{
    
    self.locationManager = [[CLLocationManager alloc] init];
    
    //是否具有定位权限
    int status=[CLLocationManager authorizationStatus];
    
    //请求权限
    if ([[UIDevice currentDevice].systemVersion floatValue] >= 8)
    {
        //由于IOS8中定位的授权机制改变 需要进行手动授权
        
        //获取授权认证
        [self.locationManager requestAlwaysAuthorization];
    }
    
    //试验
    if (status < 3 || ![CLLocationManager locationServicesEnabled]){
        
        UIAlertController * alertController = [UIAlertController alertControllerWithTitle:@"The user is not allowed to turn on the location service" message:@"Please turn on location service" preferredStyle:UIAlertControllerStyleAlert];
        
        UIAlertAction * confirmAction = [UIAlertAction actionWithTitle:@"Setting" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            
            NSURL *url = [NSURL URLWithString:UIApplicationOpenSettingsURLString];
            if ([[UIApplication sharedApplication] canOpenURL:url])
            {
                [[UIApplication sharedApplication] openURL:url];
                
            }
            
        }];
        
        UIAlertAction * cancelAction = [UIAlertAction actionWithTitle:@"Cancel" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
            
        }];
        
        [alertController addAction:confirmAction];
        [alertController addAction:cancelAction];
        
        [self presentViewController:alertController animated:YES completion:nil];
        
    }else{
        
        
        
    }
    
}

#pragma mark 查找位置
-(void)searchLocation{
    
    [SVProgressHUD showWithStatus:@"Loading..."];
    
    if (!_selectedSerialNumber) {
        
        _selectedSerialNumber = self.userModel.selectedDeviceSerialNumber;
        
    }
    
    if (!_isSetting) {
        
        _selectedSerialNumber = self.userModel.selectedDeviceSerialNumber;
        
    }
    
    NSLog(@"selectedSerialNumber %@",_selectedSerialNumber);
    
    [NetworkCommand getLastStatusDataForSerialNumber:self.selectedSerialNumber Success:^(NSArray *responseObject) {
        
        NSArray *responseObject1 = responseObject;
        
        NSLog(@"selectedSerialNumber2 %@",_selectedSerialNumber);
        
        [NetworkCommand getLastTrackPoiDataBySnsForSerialNumber:self.selectedSerialNumber Success:^(NSArray *responseObject) {
            
            //判断有无数据
            if (responseObject.count > 0) {
                
                if ([[responseObject firstObject] class] == [NSNull class] || [[responseObject1 firstObject] class] == [NSNull class]) {
                    
                    [SVProgressHUD showErrorWithStatus:@"No Data."];
                    
                    [SVProgressHUD dismissWithDelay:1];
                    
                    return;
                    
                }
                
            }else{
                
                [SVProgressHUD showErrorWithStatus:@"No Data."];
                
                [SVProgressHUD dismissWithDelay:1];
                
                return;
                
            }
            
            [SVProgressHUD dismiss];
            
            [self.mapView removeOverlays:self.mapView.overlays];
            
            [self.mapView removeAnnotations:self.mapView.annotations];
            
            [self addAnnotationForResponseObject:responseObject1];
            
            [self.pullUpView setUpPullUpViewForTrackPoiDataResponseObject:responseObject StatusDataResponseObject:responseObject1];
            
            [self addTwoPointLinkForResponse:responseObject1];
            
        } failure:^{
            
            [SVProgressHUD showErrorWithStatus:@"No Data."];
            
            [SVProgressHUD dismissWithDelay:1];
            
        }];
        
    } failure:^{
        
        [SVProgressHUD showErrorWithStatus:@"No Data."];
        
        [SVProgressHUD dismissWithDelay:1];
        
    }];
    
}

#pragma mark 添加路线
-(void)addTwoPointLinkForResponse:(NSArray *)response{
    
    if (![CLLocationManager locationServicesEnabled]) {
        
        [self locationEnable];
        
        return;
        
    }
    
    NSDictionary *dict = [response firstObject];
    
    NSNumber *latitude = [dict valueForKey:NC_LAT];
    
    NSNumber *longitude = [dict valueForKey:NC_LNG];
    
    CLLocationCoordinate2D locationCoordinate2D = CLLocationCoordinate2DMake([latitude doubleValue], [longitude doubleValue]);
    
    if (![WGS84TOGCJ02 isLocationOutOfChina:locationCoordinate2D]) {
        
        locationCoordinate2D = [WGS84TOGCJ02 transformFromWGSToGCJ2:locationCoordinate2D];
        
    }
    
    MKMapItem *currentLoccationMapItem = [MKMapItem mapItemForCurrentLocation];
    
    MKMapItem *locationMapItem = [[MKMapItem alloc]initWithPlacemark:[[MKPlacemark alloc]initWithCoordinate:locationCoordinate2D addressDictionary:nil]];
    
    
    
//    [MKMapItem openMapsWithItems:@[currentLoccationMapItem,locationMapItem] launchOptions:@{MKLaunchOptionsDirectionsModeKey: MKLaunchOptionsDirectionsModeDriving,MKLaunchOptionsShowsTrafficKey: [NSNumber numberWithBool:YES]}];
    
    //路线请求
    MKDirectionsRequest *request = [[MKDirectionsRequest alloc]init];
    request.source = currentLoccationMapItem;
    request.destination = locationMapItem;
    
    //发送请求
    MKDirections *directions = [[MKDirections alloc]initWithRequest:request];
    
    __block NSInteger sumDistance = 0;
    
//    [self.mapView removeOverlays:self.mapView.overlays];
    
    NSMutableArray *polylineArray = [NSMutableArray array];
    
//    _lineViewArray = nil;
    
    //计算
    [directions calculateDirectionsWithCompletionHandler:^(MKDirectionsResponse *response, NSError *error) {
        if (!error) {
            //取出一条路线
            MKRoute *route = response.routes[0];
            
            //关键节点
            for(MKRouteStep *step in route.steps)
            {
                //大头针
//                MKPointAnnotation *annotation = [[MKPointAnnotation alloc]init];
//                annotation.coordinate = step.polyline.coordinate;
//                annotation.title = step.polyline.title;
//                annotation.subtitle = step.polyline.subtitle;
                
                
                //添加大头针
//                [self.mapView addAnnotation:annotation];
                //添加路线
//                [self.mapView addOverlay:step.polyline];
                
                [polylineArray addObject:step.polyline];
                
                NSLog(@"polyline %@",step.polyline);
                
                //距离
                sumDistance += step.distance;
            }
            
            [self.mapView addOverlays:polylineArray];
            
            NSLog(@"总距离 %ld",(long)sumDistance);
            
        }
    }];
    
    
    
    
}

#pragma mark 添加大头针
-(void)addAnnotationForResponseObject:(NSArray *)responseObject{
    
    NSString *serialNumber = self.selectedSerialNumber;
    
    NSDictionary *dict = responseObject[0];
    
    NSNumber *latitude = [dict valueForKey:NC_LAT];
    
    NSNumber *longitude = [dict valueForKey:NC_LNG];
    
    
    
    
    if ([latitude floatValue] != 0 && [longitude floatValue] != 0) {
        
        
        //获取准确坐标
        CLLocationCoordinate2D location = CLLocationCoordinate2DMake([latitude floatValue], [longitude floatValue]);
        
        
        CLLocationCoordinate2D fixLocation;
        
        if (![WGS84TOGCJ02 isLocationOutOfChina:location]) {
            
            fixLocation = [WGS84TOGCJ02 transformFromWGSToGCJ2:location];
            
        }else{
            
            fixLocation = location;
            
        }
        
        
        
        self.annotation = [[KCAnnotation alloc]init];
        self.annotation.coordinate = fixLocation;
        
        //合成图片
        NSInteger powerValue = [[dict valueForKey:NC_POWER_VALUE] integerValue];
        
        UIImage *powerImage;
        
        if (powerValue >= 70) {
            
            powerImage = [UIImage imageNamed:@"ic_power_full"];
            
        }else if (powerValue < 70 && powerValue >= 20){
            
            powerImage = [UIImage imageNamed:@"ic_power_medium"];
            
        }else{
            
            powerImage = [UIImage imageNamed:@"ic_power_low"];
            
        }
        
        UIImage *iconImage = [self.userModel.deviceIconDictionary valueForKey:serialNumber];
        
        if (!iconImage) {
            
            iconImage = [UIImage imageNamed:@"ic_tracker_useractivity_yuan_2"];
            
        }
        
        NSString *deviceName = serialNumber;
        
        if ([self.userModel.changeDeviceNameDictionary valueForKey:serialNumber]) {
            
            deviceName = [self.userModel.changeDeviceNameDictionary valueForKey:serialNumber];
            
        }else{
            
            for (NSDictionary *dict in self.userModel.deviceByAccountArray) {
                
                if ([[dict valueForKey:NC_SERIAL_NUMBER] isEqualToString:serialNumber]) {
                    
                    deviceName = [dict valueForKey:NC_DISPLAY_NAME];
                    
                    break;
                }
                
            }
            
        }
        
        self.annotation.image = [self addImage:[UIImage imageNamed:@"ic_track_marker_boy_2"] toImage:iconImage powerImage:powerImage powerValue:powerValue deviceName:deviceName];
        
        
        
        [_mapView addAnnotation:_annotation];
        
        NSLog(@"add annotation %@",serialNumber);
        
        
        
        
        double eyeAltitude;
        
        if (_mapView.camera.altitude > STATIC_ALTITUDE) {
            
            eyeAltitude = STATIC_ALTITUDE;
            
        }else{
            
            eyeAltitude = _mapView.camera.altitude;
            
        }
        
        //移动到大头针位置
        MKMapCamera *mkMapCamera = [MKMapCamera cameraLookingAtCenterCoordinate:fixLocation fromEyeCoordinate:fixLocation eyeAltitude:eyeAltitude];
        
        self.nowAnnotaionMapItem = [[MKMapItem alloc]initWithPlacemark:[[MKPlacemark alloc]initWithCoordinate:fixLocation addressDictionary:nil]];
        
        if (fabs(fixLocation.latitude) <= 90 && fabs(fixLocation.longitude) < 180 ) {
            [_mapView setCamera:mkMapCamera animated:NO];
        }
//        [_mapView setCamera:mkMapCamera animated:NO];
        
        NSLog(@"altitude %f",_mapView.camera.altitude);
        
    }else{
        
        [SVProgressHUD showErrorWithStatus:@"No Data."];
        
        [SVProgressHUD dismissWithDelay:1];
        
        
        
    }
    
    
    
}

#pragma mark 合成图片

- (UIImage *)addImage:(UIImage *)image1 toImage:(UIImage *)image2 powerImage:(UIImage *)powerImage powerValue:(NSInteger)powerValue deviceName:(NSString *)deviceName{
    
    //    CGFloat circleWidth = powerImage.size.width + 15;
    
    NSDictionary *deviceNameAttributes = @{NSFontAttributeName:[UIFont systemFontOfSize:10],NSForegroundColorAttributeName:[UIColor whiteColor]};
    
    CGRect deviceNameSizeToFit = [deviceName boundingRectWithSize:CGSizeMake(CGFLOAT_MAX, 10) options:NSStringDrawingUsesDeviceMetrics attributes:deviceNameAttributes context:nil];
    
    NSLog(@"deviceNameSizeToFit %f",deviceNameSizeToFit.size.width);
    
    
    NSLog(@"image1 %f",image1.size.width);
    
    
    //info图片
    
    
    
    
    //电量string
    NSString *powerString = [NSString stringWithFormat:@"%ld%%",(long)powerValue];
    
    NSDictionary *attributes = @{NSFontAttributeName:[UIFont systemFontOfSize:10],NSForegroundColorAttributeName:[UIColor whiteColor]};
    
    CGRect sizeToFit = [powerString boundingRectWithSize:CGSizeMake(CGFLOAT_MAX, 10) options:NSStringDrawingUsesDeviceMetrics attributes:attributes context:nil];
    
    
    
    
    CGFloat infoHeight = deviceNameSizeToFit.size.height + powerImage.size.height + 15;
    
    CGFloat infoWidth;
    
    CGFloat margin;
    
    CGFloat deviceNameX;
    
    if (powerImage.size.width + sizeToFit.size.width + 5 > deviceNameSizeToFit.size.width) {
        
        infoWidth = powerImage.size.width + sizeToFit.size.width + 25;
        
        margin = (infoWidth - powerImage.size.width - sizeToFit.size.width)/2;
        
        deviceNameX = (infoWidth - deviceNameSizeToFit.size.width) / 2 ;
        
    }else{
        
        infoWidth = deviceNameSizeToFit.size.width + 20;
        
        margin = (infoWidth - powerImage.size.width - sizeToFit.size.width)/2 + 5;
        
        deviceNameX = 10;
        
    }
    
    UIGraphicsBeginImageContextWithOptions(CGSizeMake(infoWidth, infoHeight), NO, 0.0);
    
    
    
    
    
    
    UIImage *infoImage = [UIImage imageNamed:@"power&username2"];
    
    [infoImage drawInRect:CGRectMake(0, 0, infoWidth, infoHeight)];
    
    [deviceName drawAtPoint:CGPointMake(deviceNameX, 5) withAttributes:deviceNameAttributes];
    
    
    
    
    [powerString drawAtPoint:CGPointMake(margin + powerImage.size.width + 5,deviceNameSizeToFit.size.height + 10) withAttributes:attributes];
    
    [powerImage drawAtPoint:CGPointMake(margin,deviceNameSizeToFit.size.height + 10)];
    
    
    
    
    UIImage *circleImage = UIGraphicsGetImageFromCurrentImageContext();
    
    UIGraphicsEndImageContext();
    
    
    CGFloat infoImageMarginHeight = circleImage.size.height / 2;
    
    //大头针
    UIGraphicsBeginImageContextWithOptions(CGSizeMake(image1.size.width + circleImage.size.width, image1.size.height + infoImageMarginHeight), NO, 0.0);
    
    // Draw image1
    [image1 drawInRect:CGRectMake(0, infoImageMarginHeight, image1.size.width, image1.size.height)];
    
    // Draw image2
    [image2 drawInRect:CGRectMake(2, infoImageMarginHeight + 2, image1.size.width - 4, image1.size.width - 4)];
    
    [circleImage drawInRect:CGRectMake(image1.size.width, 0, circleImage.size.width, circleImage.size.height)];
    
    UIImage *resultingImage = UIGraphicsGetImageFromCurrentImageContext();
    
    UIGraphicsEndImageContext();
    
    return resultingImage;
}

//- (UIImage *)addImage:(UIImage *)image1 toImage:(UIImage *)image2 powerImage:(UIImage *)powerImage powerValue:(NSInteger)powerValue{
//    
//    CGFloat circleWidth = powerImage.size.width + 15;
//    
//    UIGraphicsBeginImageContextWithOptions(CGSizeMake(circleWidth, circleWidth), NO, 0.0);
//    
//    //画圆
//    
//    CGContextRef context = UIGraphicsGetCurrentContext();
//    [[UIColor clearColor] set];
//    CGContextFillRect(context, CGRectMake(0, 0, circleWidth, circleWidth));
//    CGContextAddEllipseInRect(context, CGRectMake(0, 0, circleWidth, circleWidth));
//    [[UIColor colorWithRed:80/255.0 green:150/255.0 blue:240/255.0 alpha:1] set];
//    CGContextFillPath(context);
//    
//    
//    
//    //电量数字
//    NSString *powerString = [NSString stringWithFormat:@"%ld%%",(long)powerValue];
//    
//    NSDictionary *attributes = @{NSFontAttributeName:[UIFont systemFontOfSize:10],NSForegroundColorAttributeName:[UIColor whiteColor]};
//    
//    CGRect sizeToFit = [powerString boundingRectWithSize:CGSizeMake(CGFLOAT_MAX, 10) options:NSStringDrawingUsesDeviceMetrics attributes:attributes context:nil];
//    
//    
//    
//    
//    [powerString drawAtPoint:CGPointMake((circleWidth-sizeToFit.size.width)/2,5) withAttributes:attributes];
//    
//    [powerImage drawAtPoint:CGPointMake((circleWidth - powerImage.size.width)/2, 5 + powerImage.size.height)];
//    
//    
//    UIImage *circleImage = UIGraphicsGetImageFromCurrentImageContext();
//    
//    UIGraphicsEndImageContext();
//    
//    
//    //大头针
//    UIGraphicsBeginImageContextWithOptions(CGSizeMake(image1.size.width + circleImage.size.width, image1.size.height + circleWidth/2), NO, 0.0);
//    
//    // Draw image1
//    [image1 drawInRect:CGRectMake(0, circleWidth/2, image1.size.width, image1.size.height)];
//    
//    // Draw image2
//    [image2 drawInRect:CGRectMake(2, circleWidth/2 + 2, image1.size.width - 4, image1.size.width - 4)];
//    
//    [circleImage drawInRect:CGRectMake(image1.size.width, 0, circleImage.size.width, circleImage.size.height)];
//    
//    UIImage *resultingImage = UIGraphicsGetImageFromCurrentImageContext();
//    
//    UIGraphicsEndImageContext();
//    
//    return resultingImage;
//}

#pragma mark - 地图控件代理方法
#pragma mark 显示大头针时调用，注意方法中的annotation参数是即将显示的大头针对象
-(MKAnnotationView *)mapView:(MKMapView *)mapView viewForAnnotation:(id<MKAnnotation>)annotation{
    //由于当前位置的标注也是一个大头针，所以此时需要判断，此代理方法返回nil使用默认大头针视图
    if ([annotation isKindOfClass:[KCAnnotation class]]) {
        static NSString *key1=@"AnnotationKey1";
        MKAnnotationView *annotationView=[_mapView dequeueReusableAnnotationViewWithIdentifier:key1];
        
        //算中心点
        CGFloat pointCenterPercent = 30.0 / ((KCAnnotation *)annotation).image.size.width;
        
        NSLog(@"pointCenterPercent %f",pointCenterPercent);
        
        //如果缓存池中不存在则新建
        if (!annotationView) {
            annotationView=[[MKAnnotationView alloc]initWithAnnotation:annotation reuseIdentifier:key1];
            annotationView.canShowCallout=true;//允许交互点击
            annotationView.calloutOffset=CGPointMake(0, 0);//定义详情视图偏移量
            annotationView.layer.anchorPoint = CGPointMake(pointCenterPercent, 1);
            annotationView.leftCalloutAccessoryView=[[UIImageView alloc]initWithImage:[UIImage imageNamed:@"icon_classify_cafe.png"]];//定义详情左侧视图
        }
        
        //修改大头针视图
        //重新设置此类大头针视图的大头针模型(因为有可能是从缓存池中取出来的，位置是放到缓存池时的位置)
        annotationView.annotation=annotation;
        annotationView.image=((KCAnnotation *)annotation).image;//设置大头针视图的图片
        
        
        return annotationView;
    }else {
        return nil;
    }
}

#pragma mark 用户位置改变调用 更新线路
-(void)mapView:(MKMapView *)mapView didUpdateUserLocation:(MKUserLocation *)userLocation{
    
    if (![CLLocationManager locationServicesEnabled]) {
        
        [self locationEnable];
        
        return;
        
    }
    
    if (!_nowAnnotaionMapItem) {
        
        return;
        
    }
    
//    CLLocationCoordinate2D locationCoordinate2D = self.annotation.coordinate;
    
    MKMapItem *currentLoccationMapItem = [MKMapItem mapItemForCurrentLocation];
    
//    MKMapItem *locationMapItem = [[MKMapItem alloc]initWithPlacemark:[[MKPlacemark alloc]initWithCoordinate:locationCoordinate2D addressDictionary:nil]];
    
    double eyeAltitude;
    
    if (_mapView.camera.altitude > STATIC_ALTITUDE) {
        
        eyeAltitude = STATIC_ALTITUDE;
        
    }else{
        
        eyeAltitude = _mapView.camera.altitude;
        
    }
    
    //移动到当前位置
    MKMapCamera *mkMapCamera = [MKMapCamera cameraLookingAtCenterCoordinate:userLocation.coordinate fromEyeCoordinate:userLocation.coordinate eyeAltitude:eyeAltitude];
    
    [_mapView setCamera:mkMapCamera animated:NO];
    
    //路线请求
    MKDirectionsRequest *request = [[MKDirectionsRequest alloc]init];
    request.source = currentLoccationMapItem;
    request.destination = self.nowAnnotaionMapItem;
    
    //发送请求
    MKDirections *directions = [[MKDirections alloc]initWithRequest:request];
    
    __block NSInteger sumDistance = 0;
    
//    [self.mapView removeOverlays:self.mapView.overlays];
//    [_updatePolylineArray removeAllObjects];
    NSMutableArray *updatePolylineArray = [NSMutableArray array];
    
    //计算
    [directions calculateDirectionsWithCompletionHandler:^(MKDirectionsResponse *response, NSError *error) {
        if (!error) {
            //取出一条路线
            MKRoute *route = response.routes[0];
            
            //关键节点
            for(MKRouteStep *step in route.steps)
            {
                //添加路线
//                [self.mapView addOverlay:step.polyline];
                
                [updatePolylineArray addObject:step.polyline];
                
                NSLog(@"polyline %@",step.polyline);
                
                //距离
                sumDistance += step.distance;
            }
            
            [self.mapView removeOverlays:self.mapView.overlays];
            
            [self.mapView addOverlays:updatePolylineArray];
            
            NSLog(@"总距离 %ld",(long)sumDistance);
            
        }
    }];

    
}

#pragma mark 画线
-(MKOverlayRenderer *)mapView:(MKMapView *)mapView rendererForOverlay:(id<MKOverlay>)overlay{
    
    //绘制线条
    if ([overlay isKindOfClass:[MKPolyline class]])
    {
        
//        [self.mapView removeOverlays:self.lineViewArray];
        
//        [self.mapView removeOverlays:self.mapView.overlays];
        
        MKPolylineRenderer *polylineRender = [[MKPolylineRenderer alloc]initWithPolyline:overlay];
        
        polylineRender.strokeColor = [UIColor redColor];
        
        polylineRender.lineWidth = 3;
        
        [self.lineViewArray addObject:polylineRender];
        
        return polylineRender;
    }
    
    return nil;
    
    
}

//- (MKOverlayView *)mapView:(MKMapView *)mapView viewForOverlay:(id <MKOverlay>)overlay
//{
//
//    //绘制线条
//    if ([overlay isKindOfClass:[MKPolyline class]])
//    {
//        
//        [self.mapView removeOverlays:self.mapView.overlays];
//        
//        MKPolylineRenderer *polylineRender = [[MKPolylineRenderer alloc]initWithPolyline:overlay];
//        
//        polylineRender.strokeColor = [UIColor redColor];
//        
//        polylineRender.lineWidth = 3;
//        
//        return (MKOverlayView *)polylineRender;
//    }
//    
//    return nil;
//}

#pragma mark 卫星地图按钮点击事件
- (IBAction)changeMapType:(id)sender {
    
    if (self.satelliteButton.selected) {
        
        self.mapView.mapType = MKMapTypeStandard;
        
    }else{
        
        self.mapView.mapType = MKMapTypeSatellite;
        
    }
    
    
    self.satelliteButton.selected = !self.satelliteButton.selected;
    
}

#pragma mark 全屏按钮点击事件
- (IBAction)mapFullScreen:(id)sender {
    
    if (self.fullScreenButton.selected) {
        
        [self.navigationController setNavigationBarHidden:NO animated:YES];
        
        
    }else{
        
        
        [self.navigationController setNavigationBarHidden:YES animated:YES];
        
        
    }
    
    
    self.fullScreenButton.selected = !self.fullScreenButton.selected;
    
}

#pragma mark 打开收起label
- (IBAction)touchTopArrowButton:(id)sender {
    
    if (!self.topArrowButton.selected) {
        
        [self.topLabel setText:@"Get latest location with lower accuracy.But long device working time"];
        
    }else{
        
        [self.topLabel setText:@""];
        
    }
    
    self.topArrowButton.selected = !self.topArrowButton.selected;
    
}

- (IBAction)touchBottomArrowButton:(id)sender {
    
    if (!self.bottomArrowButton.selected) {
        
        [self.bottomLabel setText:@"Get latest location with higher accuracy.But short device working time"];
        
    }else{
        
        [self.bottomLabel setText:@""];
        
    }
    
    self.bottomArrowButton.selected = !self.bottomArrowButton.selected;
    
}

#pragma mark 点击locationButton
- (IBAction)touchLocationButton:(id)sender {
    
    [self searchLocation];
    
}

#pragma mark CurrentGPSLocation
- (IBAction)touchCurrentGPSLocation:(id)sender {
    
    [self.msgCommand getMessagePhoneNumberForSerialNumber:self.selectedSerialNumber Delegate:self title:MC_TITLE_CURRENT_GPS_LOCATION body:MC_BODY_CURRENT_GPS_LOCATION];
    
}


#pragma mark CurrentLBSLocation
- (IBAction)touchCurrentLBSLocation:(id)sender {
    
    [self.msgCommand getMessagePhoneNumberForSerialNumber:self.selectedSerialNumber Delegate:self title:MC_TITLE_CURRENT_LBS_LOCATION body:MC_BODY_CURRENT_LBS_LOCATION];
    
    
    
}

#pragma mark 点击列表按钮
- (IBAction)toucTotalDeviceButton:(id)sender {
    
    TotalDeviceSelectedViewController *totalDeviceSelectedViewController = [[TotalDeviceSelectedViewController alloc]init];
    
    [self.navigationController showViewController:totalDeviceSelectedViewController sender:nil];
    
}


/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
